<template>
  <CommonPage title="数据权限组定义" content-row>
    <div class="flex-1 flex flex-col overflow-hidden">
      <div class="mb-4">
        <a-button type="primary" @click="showCreateModal">新增数据权限组</a-button>
      </div>
      <div class="flex-1 overflow-hidden">
        <SlTable
          :columns="columns"
          row-key="id"
          :data-source="tableData"
          :pagination="pagination"
          :loading="tableLoading"
          :row-selection="{
            type: 'radio',
            selectedRowKeys,
            onChange,
          }"
          :custom-row="customRow"
        >
          <template #bodyCell="{ column, record }">
            <div v-if="column.key === 'oper'">
              <a @click="showUpdateModal(record)">编辑</a>
              <a class="ml-2 text-red-400" @click="handleDelete(record)">删除</a>
            </div>
          </template>
        </SlTable>
      </div>
    </div>
    <div class="w-108 ml-4 flex flex-col">
      <div class="py-2.5 font-semibold text-xl mb-1"> {{ curSelDgName }}数据权限 </div>
      <div class="flex-1 overflow-hidden">
        <a-tabs v-model:activeKey="activeKey" type="card" size="small" class="fit-tab">
          <a-tab-pane v-for="el in tabData" :key="el.key" :tab="el.name">
            <a-skeleton v-if="el.loading" loading active :avatar="false"></a-skeleton>
            <a-tree
              v-else-if="el.authData.length > 0 && curSelDgName"
              :tree-data="el.authData"
              block-node
              show-line
              show-icon
              default-expand-all
              :field-names="el.fieldNames"
            >
            </a-tree>
            <sl-empty
              v-else
              class="h-full flex items-center justify-center flex-col"
              :description="curSelDgName ? '暂无数据' : '请先选择数据权限组'"
            ></sl-empty>
          </a-tab-pane>
        </a-tabs>
      </div>
    </div>
    <CURDDialog
      id-key="id"
      create-title="新增权限组"
      update-title="编辑权限组"
      delete-message="确认删除该权限组吗？"
      :show-options="showOptions"
      :model="model"
      :model-form-setting="modelFormSetting"
      :table-data="tableData"
      :curd="curd"
      :reload-table="reloadTable"
      @before-ok="beforeOk"
      @open="handleOpen"
    />
  </CommonPage>
</template>
<script setup lang="ts">
import { computed, h, ref, watch } from "vue";
import { Api, getDeptList, getDictOptions } from "/@/api/main/system";
import { useCURD } from "/@/hooks/useCURD";
import { TableProps } from "ant-design-vue";
import { filterTreeDataByIds, loopItem } from "/@/utils/treeData";
import { DataGroupItem, DeptItem, DeptType, DictTypeCode, RoleItem } from "/@/api/main/system/models";
import {
  CURDAction,
  CURDModalEvent,
  FormItemComponentType,
  FormItemData,
  ShowCURDModalOptions,
} from "/@/components/CURDDialog/models";
import { PatternKey } from "/@/utils/verify";
import ChooseDataPermission from "./ChooseDataPermission.vue";
import { TabItem, TabKey, getTabData } from "./tabData";
import { SelectOptionItem } from "/@/types/antd";
import { cloneDeep } from "lodash-es";

/**
 * 权限表格
 */
const columns = ref<TableProps<DataGroupItem>["columns"]>([
  {
    title: "权限组编号",
    dataIndex: "code",
  },
  {
    title: "权限组名称",
    dataIndex: "name",
  },
  {
    title: "操作",
    key: "oper",
    width: 100,
  },
]);

const { pagination, tableData, tableLoading, curd, reloadTable } = useCURD<DataGroupItem>({
  getPageUrl: Api.dataGroupPage,
  cudUrl: Api.dataGroup,
  onLoadSuccess(data) {
    if (selectedRowKeys.value.length > 0) {
      const key = selectedRowKeys.value[0];
      const finded = data.find((el) => el.id === key);
      if (finded) {
        selectedRowKeys.value = [...selectedRowKeys.value];
      } else {
        selectedRowKeys.value = [];
      }
    }
  },
});

const selectedRowKeys = ref<number[]>([]);
function onChange(keys) {
  selectedRowKeys.value = keys;
}
function customRow(record: RoleItem) {
  return {
    onclick: () => {
      selectedRowKeys.value = [record.id];
    },
  };
}
const curSelDgName = computed(() => {
  if (selectedRowKeys.value.length > 0) {
    const target = tableData.value.find((item) => item.id === selectedRowKeys.value[0]);
    if (target) {
      return target.name;
    }
  }
  return "";
});
/**
 * 增加修改弹窗
 */
const showOptions = ref<ShowCURDModalOptions>();
const model = ref<Partial<DataGroupItem>>({
  name: "",
  code: "",
  dataIds: {
    deptIds: [],
    dictIds: [],
  },
});
// watch(
//   model,
//   () => {
//     console.log("==>model watch", model);
//   },
//   { deep: true }
// );
const modelFormSetting: FormItemData<Partial<DataGroupItem>>[] = [
  {
    key: "name",
    max: 32,
    pattern: PatternKey.name,
    required: true,
    label: "名称",
  },
  {
    key: "code",
    max: 32,
    pattern: PatternKey.code,
    required: true,
    label: "编码",
  },
  {
    key: "dataIds",
    label: "数据权限",
    customComponent: h(ChooseDataPermission),
    required: false,
    requiredMes: "请选择数据权限",
  },
];
function showCreateModal() {
  showOptions.value = { action: CURDAction.CREATE };
}
function showUpdateModal(record) {
  showOptions.value = { action: CURDAction.UPDATE, record };
}
function handleDelete(record) {
  showOptions.value = { action: CURDAction.DELETE, ids: [record.id] };
}

function handleOpen({ action, record }: CURDModalEvent<Partial<DataGroupItem>>) {
  if (action === CURDAction.UPDATE && record) {
    record.dataIds = {
      deptIds: record.deptIds ? record.deptIds.split(",").map((el) => +el) : [],
      dictIds: record.dictIds ? record.dictIds.split(",").map((el) => +el) : [],
    };
  }
}
function beforeOk({ model, action }: CURDModalEvent<Partial<DataGroupItem>>) {
  if (model) {
    if (model.dataIds) {
      model.deptIds = model.dataIds.deptIds.join(",");
      model.dictIds = model.dataIds.dictIds.join(",");
      delete model.dataIds;
    }
  }
}
/**
 * tab
 */
const tabData = ref<TabItem[]>(getTabData());
const activeKey = ref<TabKey>("company");
watch([selectedRowKeys, activeKey], async ([rowKeys, tabKey]) => {
  let target = tabData.value.find((el) => el.key === tabKey);
  if (target) {
    if (target.data.length === 0) {
      target.loading = true;
      let data: SelectOptionItem[] | DeptItem[] | null | undefined = [];
      if (tabKey === "company" || tabKey === "cooperation") {
        data = await getDeptList({ type: target.type as DeptType });
      } else {
        data = await getDictOptions({ typeCode: target.type as DictTypeCode });
      }
      target.loading = false;
      if (data) {
        target.data = data;
      }
    }
    //再处理权限数据
    if (rowKeys.length > 0) {
      const id = rowKeys[0];
      const item = tableData.value.find((el) => el.id === id);
      if (item) {
        let keyName = "";
        let authIds: number[] = [];
        if (tabKey === "company" || tabKey === "cooperation") {
          keyName = "id";
          authIds = item.deptIds.split(",").map((el) => +el);
        } else {
          keyName = "value";
          authIds = item.dictIds.split(",").map((el) => +el);
        }
        // console.log("==============>filterTreeDataByIds", target.data, authIds);
        const authData = filterTreeDataByIds(target.data as SelectOptionItem[], authIds, keyName);
        target.authData = authData;
      }
    }
  }
});
</script>
